<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Pay;
use app\common\library\Refund;
use app\common\model\events\Events;
use app\common\model\events\Sign;
use app\common\model\Feedback;
use app\common\model\LevelConfig;
use app\common\model\MoneyLog;
use app\common\model\Photo;
use app\common\model\User;
use think\Db;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['index', 'events_lists', 'events_info', 'photo_list'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $data = [
            'logo' => image_processing('logo', config('site.logo')),
            'site_name' => config('site.site_name'),
            'site_banner' => image_processing('site_banner', config('site.site_banner')),
            'qr_code' => image_processing('qr_code', config('site.qr_code')),
            'site_tag' => config('site.site_tag'),
            'content' => config('site.content'),
        ];

        $this->success('请求成功', $data);
    }

    /**
     * @Author LK
     * @ApiTitle (活动列表)
     * @ApiMethod (GET)
     * @ApiParams (name="state", type="integer", required=true, sample="", description="状态值:1=进行中,2=已结束")
     * @ApiParams (name="keywords", type="integer", required=true, sample="", description="关键字")
     * @ApiParams (name="city", type="integer", required=true, sample="", description="城市")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function events_lists()
    {
        $param = request()->get();
        extract($param);
        $model = new Events;
        if (isset($state) && $state) {
            $model->where('state', $state);
        }
        if (isset($keywords) && $keywords) {
            $model->whereLike('title', '%' . $keywords . '%');
        }
        if (isset($city) && $city) {
            $model->whereLike('address', '%' . $city . '%');
        }
        $lists = $model->with(['sign' => function ($q) {
            $q->where('pay_status', '10');
        }])->order('weigh desc')->paginate();
        foreach ($lists as $v) {
            $v->sign_num = Sign::where('e_id', $v->id)->where('pay_status', '10')->sum('num');
            $v->is_bao = false;
            if (isset($v->sign) && $v->sign) {
                foreach ($v->sign as $vv) {
                    $data = User::get($vv->user_id);
                    $vv->avatar = $data->avatar;
                }
            }
            if ($this->auth->isLogin()) {
                $userInfo = User::get($this->auth->id);
                $v->pay_fee = LevelConfig::getVipFee($v->price, $userInfo->level);
                $v->is_bao = Sign::where('e_id', $v->id)->where('pay_status', '10')->where('user_id', $this->auth->id)->count() ? true : false;
            }
        }

        $this->success('', $lists);
    }
    /**
     * @Author LK
     * @ApiTitle (活动详情)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function events_info()
    {
        $param = request()->get();
        extract($param);
        $data = Events::get($id);
        $data->is_bao = false;
        if ($this->auth->isLogin()) {
            $userInfo = User::get($this->auth->id);
            $data->pay_fee = LevelConfig::getVipFee($data->price, $userInfo->level);
            $data->is_bao = Sign::where('e_id', $data->id)->where('pay_status', '10')->where('user_id', $this->auth->id)->count() ? true : false;
        }
        $this->success('', $data);
    }

    /**
     * @Author LK
     * @ApiTitle (活动报名)
     * @ApiMethod (POST)
     * @ApiParams (name="e_id", type="integer", required=true, sample="", description="活动id")
     * @ApiParams (name="num", type="integer", required=true, sample="", description="报名人数")
     * @ApiParams (name="name", type="string", required=true, sample="", description="真实姓名")
     * @ApiParams (name="sex", type="string", required=true, sample="", description="性别")
     * @ApiParams (name="mobile", type="string", required=true, sample="", description="联系电话")
     * @ApiParams (name="content", type="string", required=true, sample="", description="身份证号")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function events_sign()
    {
        $param = request()->param();
        extract($param);
        $events = Events::get($e_id);
        if (time() > $events->endtime) {
            $this->error('报名时间截止');
        }
        $total = Sign::where('e_id', $e_id)->where('pay_status', '10')->sum('num');
        if (bcadd($total, $num, 0) > $events->num) {
            $this->error('报名名额不足');
        }
        $userInfo = User::get($this->auth->id);
        Db::startTrans();
        try {
            $model = new Sign;
            $param['pay_fee'] = bcmul(LevelConfig::getVipFee($events->price, $userInfo->level), $num, 2);
            $param['orderid'] = sn('events_sign', 'orderid', 'SG');
            $param['user_id'] = $this->auth->id;
            $res = $model->allowField(true)->save($param);
            if ($res) {
                queue('app/common/job/EventsSign', $model->id, 300, 'eventsSign1272');
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('支付失败：' . $e->getMessage());
        }
        $this->success('', $model->id);
    }
    /**
     * @Author LK
     * @ApiTitle (我的报名)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function my_events()
    {
        $param = request()->get();
        extract($param);
        $model = new Sign;
        $lists = $model->with(['events' => function ($q) {
            $q->where('starttime', '>', time());
        }])->where('pay_status', '10')->where('user_id', $this->auth->id)->order('paytime desc')->paginate();
        $this->success('', $lists);
    }
    /**
     * @Author LK
     * @ApiTitle (报名详情)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="订单id")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function my_events_info()
    {
        $param = request()->get();
        extract($param);
        $model = new Sign;
        $lists = $model->get($id);
        $this->success('', $lists);
    }
    /**
     * @Author LK
     * @ApiTitle (取消报名)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function cancel_sign()
    {
        $param = request()->param();
        extract($param);
        $time = time();
        $order = Sign::get($id);
        if (!$order || !isset($order->e_id)) {
            $this->error('参数错误');
        }
        $data = Events::get($order->e_id);
        // if ($time > $data->endtime) {
        //     $this->error('报名已结束，无法取消');
        // }
        // dd($time < $data->starttime - 86400);

        if ($data->cancel > 0 && $time > $data->starttime - 86400) {
            $refund_fee = bcsub($order->pay_fee, bcmul($order->pay_fee, bcdiv($data->cancel, 100, 2), 2), 2);
        } else {
            $refund_fee = $order->pay_fee;
        }
        Db::startTrans();
        try {
            if ($order->pay_type == 1) {
                Refund::refund($order->transaction_id, $order->pay_fee, $refund_fee);
            } else {
                $order->pay_status = '-1';
                $order->canceltime = time();
                $order->cancel_fee =  $refund_fee;
                $order->save();
                if ($refund_fee > 0) {
                    MoneyLog::income($order->user_id, $refund_fee, 1, 502, $order->orderid);
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            dd($e);
            $this->error('退款失败：' . $e->getMessage());
        }
        $this->success('退款成功');
    }
    /**
     * @Author LK
     * @ApiTitle (相册列表)
     * @ApiMethod (get)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function photo_list()
    {
        $lists = Photo::order('activitytime asc')->paginate();
        $this->success('', $lists);
    }
    /**
     * @Author LK
     * @ApiTitle (相册详情)
     * @ApiMethod (get)
     * @ApiParams (name="id", type="int", required=true, sample="", description="id")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function photo_info()
    {
        $param = request()->param();
        extract($param);
        $data = Photo::get($id);
        $this->success('', $data);
    }
    /**
     * @Author LK
     * @ApiTitle (意见反馈)
     * @ApiMethod (POST)
     * @ApiParams (name="content", type="string", required=true, sample="", description="意见内容")
     * @ApiParams (name="images", type="string", required=true, sample="", description="图片")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function pub_idea()
    {
        $param = request()->param();
        extract($param);
        $param['user_id'] = $this->auth->id;
        $model = new Feedback($param);
        $res = $model->allowField(true)->save();
        if ($res) {
            $this->success('发布成功');
        }
        $this->error('发布失败');
    }
}
